package com.talent.jiwen.teacher;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.talent.jiwen.R;
import com.talent.jiwen.base.BaseActivity;
import com.talent.jiwen.http.common.ActivityLifeCycleEvent;
import com.talent.jiwen.http.common.ApiFactory;
import com.talent.jiwen.http.common.HttpUtil;
import com.talent.jiwen.http.common.ProgressSubscriber;
import com.talent.jiwen.http.result.Member;
import com.talent.jiwen.http.result.PayInfo;
import com.talent.jiwen.ui.widgets.LoadingDialog;
import com.talent.jiwen.util.FileUtils;
import com.talent.jiwen.util.ImageUtil;
import com.talent.jiwen.util.LogUtil;
import com.talent.jiwen.util.SPUtil;
import com.talent.jiwen.util.Validators;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import cn.jzvd.JZVideoPlayer;
import cn.jzvd.JZVideoPlayerStandard;
import pl.droidsonroids.gif.GifImageView;
import rx.Observable;

public class OrderDetailActivity extends BaseActivity {
    @BindView(R.id.videoDesTv)
    TextView videoDesTv;
    @BindView(R.id.videoplayer)
    JZVideoPlayerStandard videoplayer;
    @BindView(R.id.contentTv)
    TextView contentTv;
    @BindView(R.id.imgRecyclerView)
    RecyclerView imgRecyclerView;
    @BindView(R.id.teamRecyclerView)
    RecyclerView teamRecyclerView;
    @BindView(R.id.memberLayout)
    LinearLayout memberLayout;
    @BindView(R.id.downLoadLayout)
    LinearLayout downLoadLayout;
    @BindView(R.id.loadingView)
    GifImageView loadingView;
    @BindView(R.id.contentLayout)
    LinearLayout contentLayout;

    private String courseLoadUrl = "";
    private String orderId;
    private static final String PARAM_ORDER_ID = "param.order.id";

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_order_detail;
    }

    @Override
    public String titleName() {
        return getString(R.string.course_detail);
    }

    @Override
    protected void initData() {
        orderId = getIntent().getStringExtra(PARAM_ORDER_ID);

        FileDownloader.setup(mContext);//初始化下载

        mHeadRightText.setVisibility(View.GONE);
        mHeadRightText.setTextColor(ContextCompat.getColor(OrderDetailActivity.this , R.color.common_app_color));
        mHeadRightText.setText("申诉");
        mHeadRightText.setTextSize(TypedValue.COMPLEX_UNIT_SP , 15);
        mHeadRightText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                OrderAppealActivity.startOrderAppealActivity(OrderDetailActivity.this ,OrderAppealActivity.APPEAL_ORDER , orderId);
            }
        });
        mHeadRightText.setVisibility(View.GONE);

        downLoadLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                downLoadVideo(courseLoadUrl);

            }
        });
        getOrderDetail();
    }

    /**订单详情
     *
     */
    private void getOrderDetail() {
        Map<String, String> map = new HashMap<>();
        map.put("orderId", orderId);
        map.put("studentId", SPUtil.getUserId());
        Observable observable = ApiFactory.getEducationApiSingleton().getOrderPayInfo(SPUtil.getToken(),map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<PayInfo>(this) {
            @Override
            protected void _onNext(PayInfo payInfo) {

                PayInfo.OrderPayInfo orderPayInfo = payInfo.getOrderPayInfo();

                if (orderPayInfo != null) {

                    if (Validators.isEmpty(orderPayInfo.getVideoUrl())){
                        videoDesTv.setVisibility(View.VISIBLE);
                        videoplayer.setVisibility(View.GONE);
                        downLoadLayout.setVisibility(View.GONE);
                    }else{
                        videoDesTv.setVisibility(View.GONE);
                        videoplayer.setVisibility(View.VISIBLE);
                        downLoadLayout.setVisibility(View.VISIBLE);

                        if (FileUtils.fileExist(FileUtils.getVideoFileName(orderPayInfo.getVideoUrl()))){
                            videoplayer.setUp(FileUtils.getVideoFileName(orderPayInfo.getVideoUrl()), JZVideoPlayerStandard.SCREEN_WINDOW_NORMAL, "");
                        }else{
                            videoplayer.setUp(orderPayInfo.getVideoUrl() , JZVideoPlayerStandard.SCREEN_WINDOW_NORMAL, "");
                        }

                        setVideoCover(orderPayInfo.getVideoUrl());
//                        videoplayer.thumbImageView.setImageResource(R.mipmap.img_video_defult);

                        courseLoadUrl = orderPayInfo.getVideoUrl();

                    }

                    switch (orderPayInfo.getOrderStatus()){
                        //已支付订单和异常订单可以申诉
                        case 7:
                        case 8:
                        case 10:
                            mHeadRightText.setVisibility(View.VISIBLE);
                            break;
                         default:
                             mHeadRightText.setVisibility(View.GONE);
                             break;
                    }

                    if (!Validators.isEmpty(orderPayInfo.getQuestionIntroduction())){
                        contentTv.setVisibility(View.VISIBLE);
                        contentTv.setText(orderPayInfo.getQuestionIntroduction());
                    }else{
                        contentTv.setVisibility(View.GONE);
                    }

                    //图片
                    if (!Validators.isEmpty(orderPayInfo.getQuestionImages())){
                        imgRecyclerView.setVisibility(View.VISIBLE);

                        final List<String> imgList = new ArrayList<>();
                        if (!Validators.isEmpty(orderPayInfo.getQuestionImages())){
                            String[] imgs = orderPayInfo.getQuestionImages().split(",");
                            for (int i = 0 ; i < imgs.length ; i++){
                                imgList.add(imgs[i]);
                            }
                        }
                        LinearLayoutManager imgLayoutManager = new LinearLayoutManager(OrderDetailActivity.this);
                        imgLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
                        imgRecyclerView.setLayoutManager(imgLayoutManager);
                        imgRecyclerView.setAdapter(new CommonAdapter<String>(OrderDetailActivity.this , R.layout.item_order_detail_img , imgList){
                            @Override
                            protected void convert(ViewHolder holder, String s, final int position) {
                                ImageUtil.loadCorner4Image(OrderDetailActivity.this , s , (ImageView) holder.getView(R.id.imgIv));

                                holder.getView(R.id.imgIv).setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {

                                        ImageUtil.picturePreviewWithUrl(OrderDetailActivity.this, position  , imgList);
                                    }
                                });
                            }
                        });
                    }else{
                        imgRecyclerView.setVisibility(View.GONE);
                    }

                    //成员
                    if (!Validators.isEmpty(orderPayInfo.getMemberList())){
                        memberLayout.setVisibility(View.VISIBLE);

                        LinearLayoutManager teamLayoutManager = new LinearLayoutManager(OrderDetailActivity.this);
                        teamLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
                        teamRecyclerView.setLayoutManager(teamLayoutManager);
                        teamRecyclerView.setAdapter(new CommonAdapter<Member>(OrderDetailActivity.this , R.layout.item_order_detail_teammate , orderPayInfo.getMemberList()){
                            @Override
                            protected void convert(ViewHolder holder, Member member, int position) {
                                if (!Validators.isEmpty(member.getStudentHeadImage())){
                                    ImageUtil.loadCircleImage(OrderDetailActivity.this , member.getStudentHeadImage() , (ImageView)holder.getView(R.id.memberHeadIv));
                                }

                                TextView memberNameTv = (TextView)holder.getView(R.id.memberNameTv);
                                memberNameTv.setText(member.getStudentName());
                            }
                        });
                    }else{
                        memberLayout.setVisibility(View.GONE);
                    }

                    loadingView.setVisibility(View.GONE);
                    contentLayout.setVisibility(View.VISIBLE);

                } else {
                    showToast(getString(R.string.data_is_wrong));
                }
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject, false);

    }


    @Override
    public void onBackPressed() {
        if (JZVideoPlayer.backPress()) {
            return;
        }
        super.onBackPressed();
    }
    @Override
    protected void onPause() {
        super.onPause();
        JZVideoPlayer.releaseAllVideos();
    }

    /**启动该页面
     *
     * @param context
     * @param orderId
     */
    public static void startOrderDetailActivity(Context context , String orderId){
        Intent intent = new Intent();
        intent.putExtra(PARAM_ORDER_ID , orderId);
        intent.setClass(context , OrderDetailActivity.class);
        context.startActivity(intent);
    }

    /**设置视频封面
     *
     * @param url
     */
    Bitmap bitmap;
    private void setVideoCover(final String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                MediaMetadataRetriever retr = new MediaMetadataRetriever();
                retr.setDataSource(url, new HashMap<String, String>());
                bitmap = retr.getFrameAtTime();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(bitmap!=null){
                            videoplayer.thumbImageView.setImageBitmap(bitmap);
                        }else{
                            videoplayer.thumbImageView.setImageResource(R.mipmap.img_video_defult);
                        }
                    }
                });
            }
        }).start();
    }

    private void downLoadVideo(String videoUrl) {

        String path = FileUtils.getVideoFileName(videoUrl);

        if (FileUtils.fileExist(path)){
            showToast("视频已存在本地");
        }else{
            downLoadFileSingle(videoUrl , path);
        }
    }

    private void downLoadFileSingle(final String url, String path) {

        FileDownloader.getImpl().create(url)
                .setPath(path)
                .setListener(new FileDownloadListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        Log.e("aaa", "pending: ==soFarBytes===" + soFarBytes + "===totalBytes====" + totalBytes);
                    }

                    @Override
                    protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
//                        mDialog.show("下载中...");
                        LoadingDialog.show(OrderDetailActivity.this);
                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
//                        Log.e("aaa", "progress: ==soFarBytes==="+soFarBytes+"===totalBytes===="+totalBytes);
                        if (totalBytes > 0) {
//                            if (mDialog.isShowing()) {
//                                mDialog.setPrecent(soFarBytes, totalBytes);
//                            }
                            LogUtil.e("下载进度===" + soFarBytes/totalBytes);
                        }
                    }

                    @Override
                    protected void blockComplete(BaseDownloadTask task) {
                    }

                    @Override
                    protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) {

                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
//                        mDialog.dismiss();
//                        updateDownloadCount(data.getId());
//                        showBook(data);
//                        showToast("下载成功");
                        LoadingDialog.dismiss(OrderDetailActivity.this);
                        showToast("下载成功");
                        videoplayer.setUp(FileUtils.getVideoFileName(url), JZVideoPlayerStandard.SCREEN_WINDOW_NORMAL, "");
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
//                        mDialog.dismiss();
                        LoadingDialog.dismiss(OrderDetailActivity.this);
                        showToast("下载失败，请重新下载");
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                    }
                }).start();
    }
}
